package com.lukebang.service.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lukebang.constant.Const;
import com.lukebang.constant.PayMethod;
import com.lukebang.constant.TypeOfIndent;
import com.lukebang.dao.CityCostRuleDAO;
import com.lukebang.dao.CustomerAddressDAO;
import com.lukebang.dao.GoodDAO;
import com.lukebang.dao.IndentDao;
import com.lukebang.dao.MerchantDAO;
import com.lukebang.dao.MerchantsWalletRecordDAO;
import com.lukebang.dao.WorkerDao;
import com.lukebang.dao.WorkerWalletRecordDao;
import com.lukebang.pojo.CityCostRule;
import com.lukebang.pojo.CustomerAddress;
import com.lukebang.pojo.Good;
import com.lukebang.pojo.Indent;
import com.lukebang.pojo.Merchant;
import com.lukebang.pojo.MerchantsWalletRecord;
import com.lukebang.pojo.Worker;
import com.lukebang.pojo.WorkerWalletRecord;
import com.lukebang.service.IGoodService;
import com.lukebang.service.IndentService;
import com.lukebang.util.DateUtils;
import com.lukebang.util.LuKeOrderNoUtil;
import com.lukebang.util.ClothCurtain.Arith;
@Service
public class IndentServiceImpl implements IndentService{
	@Resource
	private IndentDao  indentDao;
	@Resource
	GoodDAO goodDAO;
	@Autowired
	IGoodService goodsService;
	@Resource
	private CityCostRuleDAO cityCostRuleDAO;
	@Resource
	private MerchantDAO merchantDAO;
	@Resource
	private WorkerDao workerDao;
	@Resource
	private MerchantsWalletRecordDAO merchantsWalletRecordDAO;
	@Resource
	private WorkerWalletRecordDao workerWalletRecordDao;
	@Resource
	private CustomerAddressDAO customerAddressDAO;
	
	//获取取消订单后商家罚款金额
	@Override
	public Double getSubMoney(Integer  indentId){
		Double subMoney=0.0;
		if(indentId==null )return subMoney;
		Indent indent = indentDao.get(indentId);
		Map<String, Double> punishMap = cityCostRuleDAO.selectRules(indentId);
		if(punishMap==null | indent==null)return subMoney;
		if(indent.getStatus()==1){//工人已接单
			subMoney = punishMap.get("punishWorker");// 处罚的钱
		}else if(indent.getStatus()==5){//工人已出发
			subMoney = punishMap.get("punishClient");// 处罚的钱
		}
		return subMoney;
	}
	
	
	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
	public Map<String, Object> quitIndent(HttpServletRequest request, HttpSession session, Integer type,
			Integer indentId,Integer merchantId,Double subMoney) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<>();
		// 1.获取订单单信息
		Indent indent = indentDao.get(indentId);
		if (indent == null) {
			map.put("status", "1");
			map.put("message", "订单不存在 ...");
			return map;
		}
		// 给予工人的补助
		Double toWorker = 0.0;
		// 商家的钱包
		Double toMerchant = 0.0;
		// 1.所有交易记录
		Double totalFee = 0.0;
		Map<String, Object> param = new HashMap<>();
		param.put("indentId", indentId);// 测量单号
		param.put("merchantsType", 0);// 交易人身份--商家
		param.put("merchantsId", indent.getCustomerId());// 交易人id
		param.put("status", 1);// 交易状态
		List<MerchantsWalletRecord> recordList = merchantsWalletRecordDAO.selectMerchantWalletRecords(param);
		for (MerchantsWalletRecord record : recordList) {
			totalFee += record.getFinalLostMoney();
		}
		if (totalFee == 0) {
			// 未付款
			indent.setIsDelete(1);
			indentDao.updateIndentStatus(indent);
			map.put("status", "0");
			map.put("message", "订单取消成功... ");
			return map;
		} else if (totalFee > 0) {
			// 商家信息
			Merchant merchant = merchantDAO.selectMerchantByPrimaryKey(merchantId);
			if(merchant !=null){
				switch (indent.getStatus()) {
				case 0: // 等待工人接单---取消订单,并退还全款
					toMerchant = totalFee;
					break;
				case 1: // 已接单---取消订单，并罚款
				case 5: // 工人已出发--取消订单，并罚款
					toMerchant = Arith.sub(totalFee, subMoney);
					toWorker = subMoney;
					break;
				case 4: // 未付款---取消订单就Ok
				case 2: // 已完成 --取消订单就ok
				default:
					break;
				}
				if (toMerchant != 0.0) {
					//判断是否买了安心宝
					if(indent.getRelievedBao()==1){
						toMerchant-=5;
					}
					if (merchant != null) {
							Map<String, Object> paras = new HashMap<>();
							paras.put("merchantsId", merchant.getMerchantsId());
							paras.put("wallet", toMerchant + merchant.getWallet());
							merchantDAO.updateMerchantWallet(paras);
					}
					// 做交易记录
					MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
					merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
					merchantsWalletRecord.setIndentId(indentId);
					merchantsWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
							PayMethod.BALABCEPAY.getIndex(), type));
					merchantsWalletRecord.setType(type);
					merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
					merchantsWalletRecord.setSubMoney(subMoney);
					merchantsWalletRecord.setFinalLostMoney(subMoney);// 罚款金额
					merchantsWalletRecord.setFinalGetMoney(toMerchant);// 退还金额
					merchantsWalletRecord.setStatus(1);
					merchantsWalletRecord.setRemark("商家取消订单，违约罚款金额");
					merchantsWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
					merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
				}
				if (toWorker != 0.0) {
					Worker worker = workerDao.selectWorker(indent.getWorkerId());
					if (worker != null) {
						Map<String, Object> paras = new HashMap<>();
						paras.put("workerId", worker.getWorkerId());
						paras.put("wallet", toWorker + worker.getWallet());
						workerDao.updateWalletComple(paras);
					}
					// 做交易记录
					WorkerWalletRecord workerWalletRecord = new WorkerWalletRecord();
					workerWalletRecord.setWorkerId(worker.getWorkerId());
					workerWalletRecord.setIndentId(indentId);
					workerWalletRecord.setFinalGetMoney(toWorker);
					workerWalletRecord.setOrderNo(LuKeOrderNoUtil.getMerchantsOrderNo(worker.getWorkerId(),
							PayMethod.BALABCEPAY.getIndex(), type));
					workerWalletRecord.setType(8);
					workerWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
					workerWalletRecord.setStatus(1);
					workerWalletRecord.setRemark("商家取消订单，工人获取补助");
					workerWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
					workerWalletRecordDao.insertWorkerWalletRecord(workerWalletRecord);
				}
				// 修改订单状态
				indent.setIsDelete(1);//取消
				indent.setStatus(7);//取消
				indentDao.updateIndentStatus(indent);
				map.put("status", "0");
				map.put("data", toMerchant + merchant.getWallet());
				map.put("message", "订单取消成功... ");
				return map;
			}
		}
		map.put("status", "2");
		map.put("message", "订单取消失败... ");
		return map;
	}


	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
	public boolean modifyForPayIndent(HttpServletRequest request, Integer indentID, Double addPrice,
			Integer relievedBao, Integer crampetNumber, Integer fourClawNumber, Integer motorNumber,Double totalPrice,
			HttpSession session) {
		// TODO Auto-generated method stub
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		Indent indent =indentDao.get(indentID);
		if(indent==null)return false;
		indent.setBigouNum(crampetNumber==null ?0:crampetNumber);
		indent.setSizhuagouNum(fourClawNumber==null ?0:fourClawNumber);
		indent.setMotorNum(motorNumber==null ?0:motorNumber);
		/**
		 * 查询出商人和工人不同的订花费规则
		 */
		CustomerAddress customerAddress = customerAddressDAO.selectCustomerAddressByIndent(indentID);
		CityCostRule cityCostRuleForMerchant = cityCostRuleDAO
				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 0);
		CityCostRule cityCostRuleForWorker = cityCostRuleDAO
				.selectCostRuleByCityCode(customerAddress.getCuAddressCodeStr(), 1);
		// 计算商家和工人对应的配件价格
		Double accessoryPriceForMerchant = cityCostRuleForMerchant.getCrampetPrice() * crampetNumber
				+ cityCostRuleForMerchant.getFourClawPrice() * fourClawNumber
				+ cityCostRuleForMerchant.getMotorPrice() * motorNumber;
		Double accessoryPriceForWorker = cityCostRuleForWorker.getCrampetPrice() * crampetNumber
				+ cityCostRuleForWorker.getFourClawPrice() * fourClawNumber
				+ cityCostRuleForWorker.getMotorPrice() * motorNumber;

		String lukebang_order_num=null;
		if(indent.getType()==0){
			;
		}else if(indent.getType()==1){
			//安装单
			 lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
					PayMethod.ALIPAY.getIndex(), TypeOfIndent.INSTALL.getIndex());
			 Map<String, Object> priceMap = calculateIndentByIndentId(indent, customerAddress.getCuAddressCodeStr(),
						cityCostRuleForMerchant, cityCostRuleForWorker);
				Double merchantsPrice = Arith.add(Double.valueOf(priceMap.get("merchantsPrice").toString()),
						accessoryPriceForMerchant);
				Double indentPrice = Arith.add(Double.valueOf(priceMap.get("indentPrice").toString()), accessoryPriceForWorker);
				Double merchantsRealPrice = Double.valueOf(priceMap.get("merchantsRealPrice").toString());
				Double workerRealPrice = Double.valueOf(priceMap.get("workerRealPrice").toString());
				if (merchantsRealPrice.compareTo(cityCostRuleForMerchant.getInstallStartingFare()) >= 0) {
					merchantsPrice = merchantsRealPrice;
				} else {
					merchantsPrice = cityCostRuleForMerchant.getInstallStartingFare();
				}

				if (workerRealPrice.compareTo(cityCostRuleForWorker.getInstallStartingFare()) <= 0) {
					indentPrice = cityCostRuleForWorker.getInstallStartingFare();
				}

				if (relievedBao == null) {
					relievedBao = 0;
				}
				if (relievedBao == 1) {
					merchantsPrice = merchantsPrice + 5;
				}
				// 是否需要添加取货地址
				if (indent.getIsNeedTakeGoods() == 1) {
					merchantsPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), merchantsPrice);
					indentPrice = Arith.add((Double) cityCostRuleForMerchant.getTakeGoodsPrice(), indentPrice);
				}
				// 插入钱包数据 但是出于为激活状态
				MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
				merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
				merchantsWalletRecord.setIndentId(indent.getIndentId());
				merchantsWalletRecord.setOrderNo(lukebang_order_num);
				merchantsWalletRecord.setMainMoney(merchantsPrice);
				merchantsWalletRecord.setType(TypeOfIndent.INSTALL.getIndex());
				merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
				merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
				request.setAttribute("lukebang_tradeno", lukebang_order_num);
				request.setAttribute("lukebang_subject", "安装订单");
				request.setAttribute("lukebang_total_fee",String.valueOf(totalPrice));
				// request.setAttribute("lukebang_show_url", "0000004");
				request.setAttribute("lukebang_body", "安装订单付款");
				request.setAttribute("lukebang_returnUrl", "http://lukebang.com.cn/lukebang/indent/addInstall.htm");
				Map<String, String> extraMap = new HashMap<String, String>();
				extraMap.put("bussType", String.valueOf(TypeOfIndent.INSTALL.getName()));
				extraMap.put("indent", String.valueOf(indentID));
				extraMap.put("relievedBao", String.valueOf(relievedBao));
				extraMap.put("addPrice", String.valueOf(addPrice));
				extraMap.put("originalMerchantPrice", String.valueOf(merchantsPrice));
				extraMap.put("originalIndentPrice", String.valueOf(indentPrice));
				extraMap.put("merchantsRealPrice", String.valueOf(merchantsRealPrice));
				extraMap.put("workerRealPrice", String.valueOf(workerRealPrice));
				extraMap.put("crampetNumber", String.valueOf(crampetNumber));
				extraMap.put("fourClawNumber", String.valueOf(fourClawNumber));
				extraMap.put("motorNumber", String.valueOf(motorNumber));
				request.setAttribute("extra_common_param", JSON.toJSONString(extraMap, SerializerFeature.UseSingleQuotes));
		}else if(indent.getType()==2){
			//维修
			//测量单
			Double needPayMoney = indent.getMerchantsPrice() + addPrice + accessoryPriceForMerchant;
			if (relievedBao == null) {
				relievedBao = 0;
			}
			if (relievedBao == 1) {
				needPayMoney = needPayMoney + 5;
			}
			 lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
					PayMethod.ALIPAY.getIndex(), TypeOfIndent.MEASURE.getIndex());
			 	request.setAttribute("lukebang_total_fee", String.valueOf(needPayMoney));
				request.setAttribute("lukebang_body", "维修订单付款");
				request.setAttribute("lukebang_tradeno", lukebang_order_num);
				request.setAttribute("lukebang_subject", "维修订单");
				request.setAttribute("lukebang_returnUrl", "http://lukebang.com.cn/lukebang/indent/addRepair.htm");
				Map<String, String> extraMap = new HashMap<String, String>();
				extraMap.put("bussType", String.valueOf(TypeOfIndent.REPAIR.getName()));
				extraMap.put("indent", String.valueOf(indentID));
				extraMap.put("relievedBao", String.valueOf(relievedBao));
				extraMap.put("addPrice", String.valueOf(addPrice));
				extraMap.put("originalMerchantPrice", String.valueOf(indent.getMerchantsPrice()));
				extraMap.put("originalIndentPrice", String.valueOf(indent.getIndentPrice()));
				extraMap.put("crampetNumber", String.valueOf(crampetNumber));
				extraMap.put("fourClawNumber", String.valueOf(fourClawNumber));
				extraMap.put("motorNumber", String.valueOf(motorNumber));
				extraMap.put("merchantAccessoryPrice", String.valueOf(accessoryPriceForMerchant));
				extraMap.put("indentAccessoryPrice", String.valueOf(accessoryPriceForWorker));
				request.setAttribute("extra_common_param", JSON.toJSONString(extraMap, SerializerFeature.UseSingleQuotes));
				/**
				 * 添加钱包的日志记录 添加钱包的日志记录 添加钱包的日志记录
				 */
				MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
				merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
				merchantsWalletRecord.setIndentId(indentID);
				merchantsWalletRecord.setOrderNo(lukebang_order_num);
				merchantsWalletRecord.setMainMoney(needPayMoney);
				merchantsWalletRecord.setAddMoney(addPrice);
				merchantsWalletRecord.setType(3);
				merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
				merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
		}
		return false;
	}
	
	/**
	 * 计算刚插入的安装订单的各个价格 xiaGuanghui 2017年6月9日 上午9:38:47
	 * 
	 * @param indentId
	 */
	private Map<String, Object> calculateIndentByIndentId(Indent indent, String city,
			CityCostRule cityCostRuleForMerchant, CityCostRule cityCostRuleForWorker) {
		Map<String, Object> paramMap = new HashMap<>();
		Double merchantsPrice = 0.00;
		Double indentPrice = 0.00;
		// 获取订单的id
		Integer indentId = indent.getIndentId();
		List<Good> goodsList = goodDAO.selectAllIndentGoodByIndent(indentId);
		if (null != goodsList && goodsList.size() > 0) {
			// 计算订单旗下的所有goods的货物价格
			for (int a = 0; a < goodsList.size(); a++) {
				Good good = goodsList.get(a);
				if (good == null)
					continue;
				Map<String, Object> map = goodsService.calculateInstallIndent(good, city);
				merchantsPrice = Arith.add(merchantsPrice, (Double) map.get("merchantsPrice"));
				indentPrice = Arith.add(indentPrice, (Double) map.get("indentPrice"));
			}
		}
		paramMap.put("indentPrice", indentPrice);
		paramMap.put("merchantsPrice", merchantsPrice);
		paramMap.put("merchantsRealPrice", merchantsPrice);
		paramMap.put("workerRealPrice", indentPrice);
		return paramMap;
	}
	
	
	
	
	

}
